<template>
    <div>
        <el-container>
            <el-header>
                <el-select v-model="wsData.curSubscribe" placeholder="请选择"
                           @change="wsData.control.subscribeDisable=false" @click.once.native="handleSearch">
                    <el-option
                            v-for="item in forum.titleList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.code">
                        <el-tooltip class="item" effect="dark" :content="'社区长: '+item.districtHeadId+',状态: '+item.status" placement="top-start">
                            <span style="float: left">{{ item.title }}</span>
                        </el-tooltip>
                    </el-option>
                </el-select>
                <el-button type="primary" @click="subscribe" :disabled="wsData.control.subscribeDisable">进入论坛</el-button>
            </el-header>
            <el-main>
                <div style="height: 400px;background-color: gray">
                    <el-scrollbar
                            wrapStyle="color:'#fff';fontSize:'16px';"
                            viewStyle="color:'#fff';fontSize:'16px';background-color: gray"
                            :native="false"
                            :noresize="true"
                            tag="ul">
                        <ul>
                            <li v-for="(m,index) in forum.talkList" :key="index">{{ m.msg }}</li>
                        </ul>
                    </el-scrollbar>
                </div>
            </el-main>
            <el-footer>
                <el-row>
                    <el-col :span="18">
                        <el-input type="text" v-model="wsData.msg"
                                  placeholder="你想说"
                                  @keyup.enter.native="sendMsg"
                                  clearable
                                  :disabled="wsData.control.sendDisable"
                                  @click.capture="checkMsg"></el-input>
                    </el-col>
                    <el-col :span="6">
                        <el-button type="success" @click="sendMsg" :disabled="wsData.control.sendDisable">发送</el-button>
                    </el-col>
                </el-row>
            </el-footer>
        </el-container>
    </div>
</template>

<script>
    import SockJS from  'sockjs-client';
    import Stomp from 'stompjs';

    export default {
        name:'uForum',
        data() {
            return {
                forum:{
                    titleList:[],
                    talkList:[],
                },
                wsData:{
                    // wsServerUrl:'http://127.0.0.1:8082/websocket',
                    wsServerUrl:'http://120.77.209.135:8082/websocket',
                    wsAppPrefix:'/app/center',
                    wsTopicPrefix:'/topic/',
                    stompClient: null,
                    connected: false,
                    lastSubscribe:'',
                    curSubscribe:'',
                    msg:'',
                    control:{
                        subscribeDisable: true,
                        sendDisable: true,
                    }
                },
            };
        },
        mounted: function () {
            console.log("链接中...");
            this.connect();
        },
        beforeDestroy: function () {
            console.log("离开页面断开链接...");
            this.disconnect();
            this.$message.success('断开链接');
        },
        methods: {
            connect() {
                const _this=this;
                const socket = new SockJS(this.wsData.wsServerUrl);
                this.wsData.stompClient = Stomp.over(socket);
                const headers={

                };
                this.wsData.stompClient.connect(headers, function (frame) {
                    _this.wsData.connected=true;
                    _this.$message.success("链接成功");
                    console.log('Connected: ' + frame);
                });

            },
            subscribe(){
                const _this=this;
                if(this.wsData.lastSubscribe){
                    this.disSub(this.wsData.lastSubscribe);
                }
                this.wsData.lastSubscribe=this.wsData.wsTopicPrefix+this.wsData.curSubscribe;
                _this.wsData.stompClient.subscribe(this.wsData.wsTopicPrefix+this.wsData.curSubscribe, function (greeting) {
                    const msg=(JSON.parse(greeting.body)).content;
                    _this.forum.talkList.push({
                        msg: msg
                    });
                    console.log(msg);
                }, (err) => {
                    // 连接发生错误时的处理函数
                    console.log(err);
                });
                _this.$message.success("进入论坛");
                //更新控制
                _this.wsData.control={
                    sendDisable: false,
                    subscribeDisable: true
                };
            },
            disSub(subscribe){
                this.wsData.stompClient.unsubscribe(subscribe);
                this.forum.talkList=[];
                console.log('取消订阅：'+subscribe);
            },
            // 断开连接
            disconnect() {
                if (this.wsData.stompClient !== null) {
                    //取消订阅
                    this.disSub(this.wsData.curSubscribe);
                    //断开链接
                    this.wsData.stompClient.disconnect();
                }
                this.wsData.connected=false;
                console.log("Disconnected");
            },
            sendMsg() {
                //验证输入框是否为空
                if (this.wsData.msg){
                    const messageBody={
                        from:this.curUsername,
                        to:this.wsData.wsTopicPrefix+this.wsData.curSubscribe,
                        msg:this.wsData.msg
                    };
                    const params=JSON.stringify(messageBody);
                    this.wsData.stompClient.send(this.wsData.wsAppPrefix, {}, params);
                    //清空发送信息
                    this.wsData.msg='';
                }
            },
            checkMsg(){
                if (this.wsData.msg){
                    return true;
                }else {
                    return false;
                }
            },
            //搜索
            handleSearch(){
                const _this=this;
                this.getRequest("/forum/search",{status:1})
                    .then(resp =>{
                        if (resp && resp.data && resp.data.code === '200') {
                            const data = resp.data;
                            _this.forum.titleList=data.result;
                        }
                    })
            },
        },
        computed:{
            curUsername(){
                return this.$store.getters.curUsername;
            },
            getBaseUrl(){
                return this.$store.getters.getBaseUrl;
            }
        },
    }
</script>
<style scoped>

</style>

